""" Module to interact with redmine project managment

Example:

import redmine
redmine_page= 'http://xxx.xx.xxx.xxx:3000/projects/tritume/wiki/Wiki/edit'
attachfile= 'log.txt'

(br, page)= redmine.login(redmine_page= redmine_page)

redmine.write_wiki(browser= br, text= 'h1. Test redmine module', redmine_page= redmine_page)
redmine.attach_wiki(browser= br, page= redmine_page, attachment= attachfile)

--------------------------------------------------------------------------------
These are the fields available on the Wiki/edit:

>>> br.select_form(nr=1)
>>> for f in br.forms():
...     print(f)
... 
<GET http://143.65.172.155:3000/search/index/tritume application/x-www-form-urlencoded
  <HiddenControl(wiki_pages=1) (readonly)>
  <TextControl(q=)>>
<POST http://143.65.172.155:3000/projects/tritume/wiki/Wiki/add_attachment multipart/form-data
  <HiddenControl(authenticity_token=qtu3+29nOFSrjGizNujVFKJlbwwMmo60QIUzNeYeUmM=) (readonly)>
  <FileControl(attachments[1][file]=<No files added>)>
  <TextControl(attachments[1][description]=)>
  <SubmitControl(commit=Add) (readonly)>>

TODO:

Logout function

"""

import sys
import os
import mechanize
import ClientForm
import urlparse

def get_authorization():
    """ Read file ~/.redminepass to access the relevant server """
    try:
        passfile= open(os.path.join(os.getenv('HOME'), '.redminepass'))
    except:
        sys.exit('Cannot read file "%s". Necessary to access Redmine' %(os.path.join(os.getenv('HOME'))))
    passfile= passfile.readlines()
    login= {'host': '', 'username': '', 'password': ''}
    for line in passfile:
        line= line.strip()
        if line.startswith('host:'):
            host= line.lstrip('host:')
            host= host.lstrip()
            login['host']= host
        if line.startswith('username:'):
            usr= line.lstrip('username:')
            usr= usr.lstrip()
            login['username']= usr
        if line.startswith('password:'):
            pwd= line.lstrip('password:')
            pwd= pwd.lstrip()
            login['password']= pwd
    return(login)

def login(redmine_page):
    """ Login using the details in dict 'credentials', typically returned from get_authorization().
    credentials= {'host': '', 'username': '', 'password': ''}
    page= page within the host to access. E.g. 'http://xxx.xx.xxx.xxx:xxxx/projects/tritume/wiki/Wiki/edit'
    
    Returns the opened page and browser
    
    """
    login= get_authorization()
    url_fh = login['host']
    br = mechanize.Browser()
    br.set_handle_robots(False)
    
    # Fetching login page
    page = br.open( url_fh + 'login' )
    
    # Logging in
    br.select_form( nr=1 )
    br["username"]= login['username']
    br["password"]= login['password']
    #br["autologin"]=0
    page = br.submit()
    page = br.open( redmine_page )
    return((br, page))

def write_wiki(text, redmine_page):
    """
    Edit the wiki page accessed from the browser.
    browser: Browser as typically returned from login()
    """
    redmine_page= redmine_page.rstrip('/')
    redmine_page= redmine_page + '/edit'
    browser= login(redmine_page)[0]
    page = browser.open( redmine_page )   ## Go to this page
    browser.select_form( nr=1 )
    browser.form['content[text]']= text
    page = browser.submit()
    browser.close()
    return('done')

def attach_wiki(redmine_page, attachment, description= ''):
    """
    Attach a file to wiki page in browser.
    browser: Browser as typically returned from login()
    redmine_page: 'http://xxx.xx.xxx.xxx:xxxx/projects/tritume/wiki/Wiki/'
    """
    redmine_page= redmine_page.rstrip('/')
    redmine_page= redmine_page + '/edit'
    browser= login(redmine_page)[0]
    page = browser.open( redmine_page )   ## Go to this page
    browser.select_form( nr=1 )
    attachment_name= os.path.split(attachment)[1]
    try:
        browser.add_file( open( attachment, 'rb' ), "text/plain", attachment_name )
    except:
        print('redmine.attach_wiki: File %s not found.' %(attachment))
        return()
    browser.form['attachments[1][description]']= description
    redmine_page = browser.submit()
    browser.close()
    return(attachment_name)

def file2table(infile, sep= '\t', header= True, comment_char= '#', skip_blank= True, table_title= '', table_legend= ''):
    """ Convert a file containing a table to a string formatted to redmine wiki table.
    Args:
    infile:
        Input file to convert
    sep:
        Character separating columns
    header:
        Is first line the header? If false, the formatted table will not have headers.
        If the are comment lines, the first line is the first non commented line.
    comment_char:
        Skip rows starting with this string. Set to '' to disable skipping.
    skip_blanks:
        Should blank lines be skipped? A blank line is line='\n' or '\r' or '\n\r'. While line= '\t\n' is not blank
    table_title, table_legend:
        String with optianal title something like 'h2. Peak summary from homer/findpeaks\n'
    E.g. if infile is:
    col1    col2
    bla     bla
    
    Returns:
    |_.col1|_.col2|\n|bla|bla|
    
    The retun bvalue is string
    
    """
    try:
        tablefile= open(infile).readlines()
    except:
        return('@redmine.file2table@: File @%s@ not found.\n' %(infile)) 
    tablefile= [x.rstrip('\n\r') for x in tablefile]
    if not comment_char == '':
        tablefile= [x for x in tablefile if not x.startswith(comment_char)]
    if skip_blank is True:
        tablefile= [x for x in tablefile if not x == '']
    if header is True:
        headerline= tablefile[0].split(sep)
        headerline= ['_.' + x for x in headerline]
        tablefile[0]= sep.join(headerline)
    tablefile= ['|' + x.replace(sep, '|') + '|' for x in tablefile]
    tablefile= [table_title] + tablefile + [table_legend]
    return('\n'.join(tablefile))

def file2text(infile, text_title= '', text_legend= ''):
    """
    Returns the text in infile as string. Optionally prepend and append title and legend.
    """
    try:
        textfile= open(infile).readlines()
    except:
        return('@redmine.file2text@: File @%s@ not found.\n' %(infile)) 
    textfile= text_title + ''.join(textfile) + text_legend
    return(textfile)

def remove_attachments(redmine_wiki):
    """
    Removes all the attachments from the selected wiki page
    
    Example:
    redmine_wiki= 'http://xxx.xx.xxx.xxx:xxxx/projects/tritume/wiki/Wiki/'   ## Wiki page from whihc to remove attachments
    remove_attachments(redmine_wiki)
    
    """
    redmine_host= urlparse.urlparse(redmine_wiki)[1]
    browser= login(redmine_page= redmine_wiki)[0]
    remove_links = list(browser.links(url_regex="destroy/\d"))  ## Links to remove
    for i in range(0, len(remove_links)):
        temp_link = 'http://' + redmine_host + remove_links[i].url
        print(remove_links[i].url)
        browser.form = ClientForm.HTMLForm(action=temp_link, method="POST")
        browser.submit()
        browser.close()
        browser= login(redmine_page= redmine_wiki)[0]
    browser.close()
    
    